package com.lin.server.sharding;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;

import java.util.Collection;

/**
 * 自定义分表算法
 *
 */
public class CustomStringShardingAlgorithm implements PreciseShardingAlgorithm<String> {
    @Override
    public String doSharding(Collection<String> availableTargetNames, PreciseShardingValue<String> shardingValue) {
        String value = shardingValue.getValue();
        int suffix = value.hashCode() % availableTargetNames.size();
        for (String targetName : availableTargetNames) {
            if (targetName.endsWith(String.valueOf(suffix))) {
                return targetName;
            }
        }
        throw new UnsupportedOperationException("Cannot find appropriate sharding target for value: " + value);
    }
}

